import { createStore } from 'vuex'

/**
 * mutations和actions是什么区别？
 * 1、actions可以异步操作，如向服务端提交数据; mutations只能是同步操作。
 * getters又是作甚的
 * 1、类似于属性
 */
export const useUserCoins = createStore({
  state() {
    return {
      coins: 0,
      todos: [
        { value: '吃饭', hasDone: true },
        { value: '喝水', hasDone: false },
        { value: '接口定义', hasDone: false },
      ] as any,
    }
  },
  mutations: {
    addCoins(state, val) {
      if (!val) {
        state.coins++
      } else {
        state.coins = val
      }
    },
    reduceCoins(state) {
      state.coins--
    },
  },
  actions: {
    asyncAddCoins({ commit, state }) {
      setTimeout(() => {
        commit('addCoins', state.coins + 10)
      }, 1000)
    },
    async updateUserCoins({ commit }, val) {
      const resp = await fetch('https://example.com/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ id: 1, coins: val }),
      })
      commit('reduceCoins', resp.json())
    },
    async fetchAll({ dispatch, commit, state }) {
      await dispatch('asyncAddCoins')
      commit('reduceCoins', state.coins + 10)
    },
  },
  getters: {
    formatFee(state) {
      return `${(state.coins / 100).toFixed(2)} 元`
    },
    doneTodos(state) {
      return state.todos.filter((todo: any) => todo.hasDone == true)
    },
  },
})
